/**
 * Created by kc on 16/6/5.
 */

var logger      = require('./log.js').logger;
var jsSHA       = require('jssha');
var redis 		= require("redis");
var ezhttps     = require('./ezhttp').ezhttps;
var querystring = require('querystring');
var config 		= require('../conf/config.js');
var redisConf = config['redis']['default'];
var wxConfig    = config['wechat'];
var wxCustConfig    = config['wechatCust'];

exports.authCode = function (code,type,cb) {
	var appid;
	var secret;

	if(type == '1'){
		appid = wxConfig['appid'];
		secret = wxConfig['secret'];
	}else {
		appid = wxCustConfig['appid'];
		secret = wxCustConfig['secret'];
	}

	logger.debug(appid);
	var queryData = {
		"appid": appid,
		"secret": secret,
		"code": code,
		"grant_type":"authorization_code"
	};
	logger.debug(querystring.stringify(queryData))
	var uri = '/sns/oauth2/access_token?'+querystring.stringify(queryData);

	ezhttps('api.weixin.qq.com','GET',uri, {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},null,function(err,res){
		if(err) {
			logger.error('/sns/oauth2/access_token 失败:'+code+' ;err:'+err.message);
			cb(null,null);
		} else {
			var _res = JSON.parse(res);
			if(_res && _res['openid']) {
				cb(null, {openid:_res['openid'], access_token:_res['access_token']});
			}else{
				logger.error(res);
			}
		}
	});
};

exports.getUserInfo = function (accessToken, openid,cb) {
	var queryData = {
		"access_token": accessToken,
		"openid": openid,
		"lang": 'zh_CN'
	};

	var uri = '/sns/userinfo?'+querystring.stringify(queryData);
	ezhttps('api.weixin.qq.com','GET',uri, {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},null,function(err,res){
		if(err) {
			logger.error('/sns/userinfo 失败:'+code+' ;err:'+err.message);
			cb(null,null);
		} else {
			var _res = JSON.parse(res);
			if(_res && !_res['errcode']) {
				cb(null, _res);
			}else{
				logger.error(res);
			}
		}
	});
};

exports.getJsParams = function(url) {
	return function (cb) {
		var redisClient = redis.createClient(redisConf['port'],redisConf['host']);
		redisClient.auth(redisConf['password'],function(){});
		redisClient.select(8, function(){
			redisClient.get("ticket_jqbx", function(err, reply) {
				if(err){
					logger.error(err.message);
					cb(null, null);
					return;
				}
				logger.info('Ticket/'+reply);
				if(reply) {
					var params = sign(reply, url);
					params.appId = config['wechat']['appid'];
					cb(null, params);
				}
				cb(null, null);
			});

		});
	};
}

var createNonceStr = function () {
	return Math.random().toString(36).substr(2, 15);
};

var createTimestamp = function () {
	return parseInt(new Date().getTime() / 1000) + '';
};

var raw = function (args) {
	var keys = Object.keys(args);
	keys = keys.sort();
	var newArgs = {};
	keys.forEach(function (key) {
		newArgs[key.toLowerCase()] = args[key];
	});

	var string = '';
	for (var k in newArgs) {
		string += '&' + k + '=' + newArgs[k];
	}
	string = string.substr(1);
	return string;
};

/**
 * @synopsis 签名算法
 *
 * @param jsapi_ticket 用于签名的 jsapi_ticket
 * @param url 用于签名的 url ，注意必须动态获取，不能 hardcode
 *
 * @returns
 */
function sign (jsapi_ticket, url) {
	var ret = {
		jsapi_ticket: jsapi_ticket,
		nonceStr: createNonceStr(),
		timestamp: createTimestamp(),
		url: url
	};
	var string = raw(ret);logger.debug(string);
	shaObj = new jsSHA(string, 'TEXT');
	ret.signature = shaObj.getHash('SHA-1', 'HEX');

	return ret;
}
